package Servlet;

import com.cyy.dao.productDao;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Random;

@WebServlet("/addProductToDb")
public class addProductToDbServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String productName = request.getParameter("productName");
        int price = Integer.parseInt(request.getParameter("price"));
        int sold = Integer.parseInt(request.getParameter("sold"));
        int reserve = Integer.parseInt(request.getParameter("reserve"));
        String message;
        if(sold<0||reserve<=0||price<=0)
        {
            message="商品的数值不合理！不能为0，请检查！";
        }
        else {
            String[] names = new String[1];
            names[0] = productName;
            int[] prices = new int[1];
            int[] solds = new int[1];
            int[] reserves = new int[1];
            prices[0] = price;
            solds[0] = sold;
            reserves[0] = reserve;
//            随机生成新商品对应的图片
            Random r = new Random();
            int i1 = r.nextInt(39) + 1;
            String[] covers = new String[1];
            covers[0] = "images/product-" + i1 + ".jpg";
            productDao productDao = new productDao();
            boolean success = false;
            try {
//                将商品添加进表product
                success = productDao.addProduct(names, prices, reserves, solds, covers);
            } catch (SQLException | ClassNotFoundException throwables) {
                throwables.printStackTrace();
            }
            if (success) {
                message = "添加成功！";
            } else {
                message = "添加失败！该商品名字已经存在！";
            }
        }
        System.out.println(message);
        request.setAttribute("message",message);
        request.getRequestDispatcher("/showProduct").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }
}
